package org.example.yunpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.example.yunpicturebackend.exception.BusinessException;
import org.example.yunpicturebackend.exception.ErrorCode;
import org.example.yunpicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;


import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * url图片上传
 */
@Slf4j
@Service
public class UrlPictureUpload extends PictureUploadTemplate {
    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");

        try {
            // 1. 验证 URL 格式
            new URL(fileUrl);
            // 验证是否是合法的 URL
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }
        // 2. 校验 URL 协议
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")),
                ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址");

        // 3. 发送 HEAD 请求以验证文件是否存在
        HttpResponse response = null;
        try {
            response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            // 未正常返回，无需执行其他判断
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 4. 校验文件类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
            // 5. 校验文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long TWO_MB = 2 * 1024 * 1024L; // 限制文件大小为 2MB
                    ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        // 从 URL 中提取文件名
        return FileUtil.mainName(fileUrl);
    }
//
//    @Override
//    protected void processFile(Object inputSource, File file) throws Exception {
//        String fileUrl = (String) inputSource;
//        // 下载文件到临时目录
//        HttpUtil.downloadFile(fileUrl, file);
//
@Override
protected void processFile(Object inputSource, File file) throws Exception {
    String fileUrl = (String) inputSource;

    log.info("开始下载图片: {}", fileUrl);

    // 完全替换下载逻辑，不使用 HttpUtil.downloadFile
    int maxRetries = 3;

    for (int retryCount = 0; retryCount < maxRetries; retryCount++) {
        HttpResponse response = null;
        try {
            // 创建自定义的HTTP请求
            response = HttpUtil.createGet(fileUrl)
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
                    .header("Accept", "image/webp,image/apng,image/*,*/*;q=0.8")
                    .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
                    .header("Accept-Encoding", "gzip, deflate, br")
                    .header("Connection", "keep-alive")
                    .header("Sec-Fetch-Dest", "image")
                    .header("Sec-Fetch-Mode", "no-cors")
                    .header("Sec-Fetch-Site", "cross-site")
                    .timeout(15000)  // 15秒超时
                    .setMaxRedirectCount(10)  // 允许更多重定向
                    .execute();

            int statusCode = response.getStatus();
            log.info("HTTP响应状态码: {}", statusCode);

            if (statusCode == 200) {
                // 成功下载
                byte[] fileBytes = response.bodyBytes();
                if (fileBytes != null && fileBytes.length > 0) {
                    FileUtil.writeBytes(fileBytes, file);
                    log.info("图片下载成功，文件大小: {} bytes", fileBytes.length);
                    return; // 成功退出
                } else {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "下载的文件为空");
                }
            } else {
                // 处理不同的HTTP状态码
                String errorMsg = getErrorMessageByStatusCode(statusCode);
                if (retryCount == maxRetries - 1) {
                    // 最后一次重试失败
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,
                            "图片下载失败: " + errorMsg + " (状态码: " + statusCode + ")");
                } else {
                    log.warn("下载失败，状态码: {}, 重试 {}/{}", statusCode, retryCount + 1, maxRetries);
                }
            }
        } catch (BusinessException e) {
            if (retryCount == maxRetries - 1) throw e;
            log.warn("业务异常，重试 {}/{}: {}", retryCount + 1, maxRetries, e.getMessage());
        } catch (Exception e) {
            if (retryCount == maxRetries - 1) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR,
                        "图片下载失败: " + e.getMessage() + " (URL: " + fileUrl + ")");
            }
            log.warn("下载异常，重试 {}/{}: {}", retryCount + 1, maxRetries, e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }

        // 重试前等待
        if (retryCount < maxRetries - 1) {
            try {
                Thread.sleep(2000 * (retryCount + 1)); // 等待时间递增
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载被中断");
            }
        }
    }

    throw new BusinessException(ErrorCode.PARAMS_ERROR,
            "图片下载失败，重试" + maxRetries + "次后仍然失败");
}

    // 添加状态码错误信息映射方法
    private String getErrorMessageByStatusCode(int statusCode) {
        switch (statusCode) {
            case 400: return "请求错误";
            case 401: return "未授权访问";
            case 403: return "访问被拒绝";
            case 404: return "图片不存在";
            case 405: return "方法不被允许";
            case 408: return "请求超时";
            case 429: return "请求过于频繁";
            case 500: return "服务器内部错误";
            case 502: return "网关错误";
            case 503: return "服务不可用";
            case 504: return "网关超时";
            case 567: return "服务器拒绝访问（可能由于反爬虫机制）";
            default: return "HTTP错误 " + statusCode;
        }

    }
}